<?php
/**
 * tpAdmin [a web admin based ThinkPHP5]
 *
 * @author yuan1994 <tianpian0805@gmail.com>
 * @link http://tpadmin.yuan1994.com/
 * @copyright 2016 yuan1994 all rights reserved.
 * @license http://www.apache.org/licenses/LICENSE-2.0
 */

//------------------------
// 公开不授权控制器
//-------------------------

namespace app\domin\controller;

use app\domin\Base;
use think\Config;
use think\Db;
use think\Loader;
use think\exception\HttpException;

use com\gdl\newagk\dataobject\adminlogin\AdminloginRequestDTO;
use com\gdl\newagk\interfaces\AdminloginServiceClient;

use com\gdl\newagk\interfaces\AuthorityServiceClient;
use com\gdl\newagk\dataobject\authority\AuthorityRequestDTO; 

use com\gdl\newagk\interfaces\UnitsServiceClient;
use com\gdl\newagk\dataobject\units\UnitsDTO;
use com\gdl\newagk\dataobject\units\UnitsRequestDTO;


class Authorityc extends Base
{
	
	//查询组织结构
	public function lookeOver()
    {
		$unitid = $this->request->param('unitid') ? $this->request->param('unitid/d') : 0;//部门id  现在是用户传 改完后直接查询管理员部门完成
		$adminuserid = $this->request->param('adminuserid') ? $this->request->param('adminuserid') : 0;
		$reg = $this->request->param('reg') ? getStr($this->request->param('reg')) : '';
			try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new UnitsServiceClient(NULL);
				\ApiClient::build($api);

				$engprojectDo = new UnitsDTO();
				$engprojectDo->unitid	= $unitid;
				$engprojectDo->userid	= $adminuserid;
				$engprojectDo->reg		= $reg;
				$result = $api->lookeOver($engprojectDo);
				$plaform = [];
				if($result->code){
					/*****测试原型*****/
					$plaform = $result->datas[0];
					$nodes = $result->data;
					$datas = list_to_tree($nodes);
					$plaform['children'] = $datas;
				}
				//checkstate 1是选中 0是未选中
				$data =  ['msg'=>'获取成功','code'=>'200','data'=>[$plaform]];
			} catch (Exception $ex) {
				$data = ['msg'=>'获取失败','code'=>'400','data'=>[]];
			}
			return json_encode($data);
		
	}
	
	/*
	*添加或修改单位
	*/
	public function edit()
    {

		$data = $this->request->post();

		if (!$this->request->isPost() || empty($data['plaform_id'])) {
				$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
				return json_encode($data);
        }

		/**
		$data = [
					'plaform_id'=>4,
					'child'=>[
						['id'=>1,'name'=>'产品部','status'=>1,'child'=>[]],
						['id'=>2,'name'=>'技术部','status'=>1,'child'=>[
							['id'=>3,'name'=>'前端组','status'=>1,'child'=>[]],
							['id'=>4,'name'=>'后端组','status'=>1,'child'=>[]],
						]],
						]
					];
		**/

			$adminuserid = $this->request->param('adminuserid') ? $this->request->param('adminuserid') : 0;

			try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new UnitsServiceClient(NULL);
				\ApiClient::build($api);

				$engprojectDo = new UnitsDTO();
			
				$engprojectDo->field = json_encode($data);
				$engprojectDo->userid	= $adminuserid;
				$result = $api->edit($engprojectDo);
				//checkstate 1是选中 0是未选中
				$data =  ['msg'=>$result->message,'code'=>'200','data'=>[]];
			} catch (Exception $ex) {
				$data = ['msg'=>'操作失败','code'=>'400','data'=>[]];
			}
			return json_encode($data);
	}
	
	//资源查询
	public function resourcList()
    {
	
		$adminuserid = $this->request->param('adminuserid') ? $this->request->param('adminuserid') : 0;
		$reg = $this->request->param('reg') ? getStr($this->request->param('reg')) : '';
		$groupid = $this->request->param('groupid') ? getStr($this->request->param('groupid'),'int') : 0;
		$typesof = $this->request->param('typesof') ? getStr($this->request->param('typesof'),'int') : 0;
		$title = $this->request->param('title') ? getStr($this->request->param('title'),'string') : '';
		if(!$groupid){
			$data = ['msg'=>'缺少参数','code'=>'500','data'=>[]];
			return json_encode($data);
		}
			try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AuthorityServiceClient(NULL);
				\ApiClient::build($api);

				$engprojectDo = new AuthorityRequestDTO();
				$engprojectDo->filename['adminuserid']	= $adminuserid;
				$engprojectDo->filename['reg']			= $reg;
				$engprojectDo->filename['groupid']		= $groupid;
				$engprojectDo->filename['typesof']		= $typesof;
				$engprojectDo->filename['title']		= $title;
				$result = $api->resourcList($engprojectDo);

				if($result->code){
					/*****测试原型*****/
					if(empty($result->data)){
						$datas = [];
					} else {
						$datac = $result->data;
						$datas = $result->datas[0];
						$datas[0] = '默认部门';
						$list = [];
						foreach($datac as $v){
							$list[$v['unit_id']]['id'] = $v['unit_id'];
							$list[$v['unit_id']]['name'] = $datas[$v['unit_id']];
							$v['expand'] = $v['expand']==2 ? false : true;
							$list[$v['unit_id']]["children"][] = $v;
						}
					}
					$data =  ['msg'=>$result->message,'code'=>'200','data'=>$datas];
				} else {
					$data = ['msg'=>$result->message,'code'=>'400','data'=>[]];
				}

				
			} catch (Exception $ex) {
				$data = ['msg'=>'获取失败','code'=>'400','data'=>[]];
			}
			return json_encode($data);
		
	}
	
	
	
	/*
	*单位启用禁用
	*/
	public function unitEnabled()
    {

		$unitid = $this->request->param('unitid') ? $this->request->param('unitid/d') : 0;//部门id 这里代表的是要操作那个部门
		$adminuserid = $this->request->param('adminuserid') ? $this->request->param('adminuserid') : 0;
		$reg = $this->request->param('reg') ? getStr($this->request->param('reg')) : '';
		$status = $this->request->param('status') ? $this->request->param('status/d') : 0;
			try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new UnitsServiceClient(NULL);
				\ApiClient::build($api);

				$engprojectDo = new UnitsRequestDTO();
				$engprojectDo->unitid	= $unitid;
				$engprojectDo->userid	= $adminuserid;
				$engprojectDo->reg		= $reg;
				$engprojectDo->filename['status'] = $status;
				$result = $api->enabled($engprojectDo);

				if($result->code){
					$data =  ['msg'=>$result->message,'code'=>'200','data'=>[]];
				} else {
					$data =  ['msg'=>$result->message,'code'=>'400','data'=>[]];
				}
			} catch (Exception $ex) {
				$data = ['msg'=>'操作失败','code'=>'400','data'=>[]];
			}
			return json_encode($data);
	}
	
	
	/*
	*单位下所有权限组启用禁用
	*/
	public function listEnabled()
    {

		$unitid = $this->request->param('unitid') ? $this->request->param('unitid/d') : 0;//部门id 这里代表的是要操作那个部门
		$adminuserid = $this->request->param('adminuserid') ? $this->request->param('adminuserid') : 0;
		$reg = $this->request->param('reg') ? getStr($this->request->param('reg')) : '';
		$status = $this->request->param('status') ? $this->request->param('status/d') : 0;
		$groupsid = $this->request->param('groupsid') ? $this->request->param('groupsid/d') : 0;//权限组id
			try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new UnitsServiceClient(NULL);
				\ApiClient::build($api);

				$engprojectDo = new UnitsRequestDTO();
				$engprojectDo->unitid	= $unitid;
				$engprojectDo->userid	= $adminuserid;
				$engprojectDo->reg		= $reg;
				$engprojectDo->filename['status'] = $status;
				$engprojectDo->filename['groupsid'] = $status;
				$engprojectDo->filename['operating'] = 'status';
				$result = $api->listEnabled($engprojectDo);
				if($result->code){
					$data =  ['msg'=>$result->message,'code'=>'200','data'=>[]];
				} else {
					$data =  ['msg'=>$result->message,'code'=>'400','data'=>[]];
				}
			} catch (Exception $ex) {
				$data = ['msg'=>'操作失败','code'=>'400','data'=>[]];
			}
			return json_encode($data);
	}
	
	/*
	*单位下所有权限组启用禁用
	*/
	public function listDel()
    {

		$unitid = $this->request->param('unitid') ? $this->request->param('unitid/d') : 0;//部门id 这里代表的是要操作那个部门
		$adminuserid = $this->request->param('adminuserid') ? $this->request->param('adminuserid') : 0;
		$reg = $this->request->param('reg') ? getStr($this->request->param('reg')) : '';
		$status = $this->request->param('status') ? $this->request->param('status/d') : 0;
		$groupsid = $this->request->param('groupsid') ? $this->request->param('groupsid/d') : 0;//权限组id
		if(!$unitid){
			$data = ['msg'=>'缺少参数','code'=>'500','data'=>[]];
			
			return json_encode($data);
		}
			try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new UnitsServiceClient(NULL);
				\ApiClient::build($api);

				$engprojectDo = new UnitsRequestDTO();
				$engprojectDo->unitid	= $unitid;
				$engprojectDo->userid	= $adminuserid;
				$engprojectDo->reg		= $reg;
				$engprojectDo->filename['status'] = $status;
				$engprojectDo->filename['groupsid'] = $status;
				$engprojectDo->filename['operating'] = 'del';
				$result = $api->listEnabled($engprojectDo);
				if($result->code){
					$data =  ['msg'=>$result->message,'code'=>'200','data'=>[]];
				} else {
					$data =  ['msg'=>$result->message,'code'=>'400','data'=>[]];
				}
			} catch (Exception $ex) {
				$data = ['msg'=>'操作失败','code'=>'400','data'=>[]];
			}
			return json_encode($data);
	}
	
	
	/*
	*查询当前部门admin组具备的权限
	*/
	public function listGroup()
    {
		
			$unitid = $this->request->param('unitid') ? $this->request->param('unitid/d') : 0;//部门id 这里代表的是要操作那个部门
			$adminuserid = $this->request->param('adminuserid') ? $this->request->param('adminuserid') : 0;
			$reg = $this->request->param('reg') ? getStr($this->request->param('reg')) : '';
			$groupid = $groupsid = $this->request->param('groupsid') ? $this->request->param('groupsid/d') : 0;//权限组id
			$pid = $this->request->param('pid') ? $this->request->param('pid/d') : 0;//上级id 有这个的时候查询的就是第二级
            if (!$unitid || empty($reg) || !$adminuserid ) {
				$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
				return json_encode($data);
            }
			try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AuthorityServiceClient(NULL);
				\ApiClient::build($api);
				$engprojectDo = new AuthorityRequestDTO();
				$engprojectDo->filename['unitid']	= $unitid;
				$engprojectDo->filename['adminuserid']	= $adminuserid;
				$engprojectDo->filename['reg']	= $reg;
				$engprojectDo->filename['groupid']	= $groupid;
				$engprojectDo->filename['pid']	= $pid;
				$result = $api->accessList($engprojectDo);

				if($result->code){
					$datas = [];
					foreach($result->data as $v){
						$v['expand'] = $v['expand']==1 ? true : false;
						$datas[] = $v;
					}
			
					$results = list_to_tree($datas, "id", "pid", "children");
					$data =  ['msg'=>$result->message,'code'=>'200','data'=>$results,'groupid'=>$result->data[0][0]];
				} else {
					$data =  ['msg'=>$result->message,'code'=>'400','data'=>[]];
				}

			} catch (Exception $ex) {
				$data = ['msg'=>'操作失败','code'=>'400','data'=>[]];
			}
			return json_encode($data);	
	}

	
	public function authorized()
    {
		//$role_id = $this->request->param('id/d');
		$role_id = $this->request->param('groupsid') ? $this->request->param('groupsid/d') : 0;
		$unitsid = $this->request->param('unitsid') ? $this->request->param('unitsid/d') : 0;
		$data =  ['msg'=>'操作异常','code'=>'500','data'=>[]];
		if ($this->request->isPost()) {
			$datas = $this->request->post();
			try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AuthorityServiceClient(NULL);
				\ApiClient::build($api);

				$engprojectDo = new AuthorityRequestDTO();
				$engprojectDo->filename = $datas["node"]; //这个记得处理 只能是一维数组
				$engprojectDo->filename['role_id']	= $role_id;
				$engprojectDo->filename['resourc']	=  json_encode($datas["resourc"]);//资源
				$engprojectDo->id = $unitsid;
				$result = $api->authorized($engprojectDo);

				//checkstate 1是选中 0是未选中
				if($result->code){
					$data =  ['msg'=>'成功','code'=>'200','data'=>[]];
				} else {
					$data =  ['msg'=>'失败','code'=>'400','data'=>[]];
				}
			} catch (Exception $ex) {
				$data =  ['msg'=>'失败','code'=>'500','data'=>[]];
			}
			
		}
		return json_encode($data);
	}
	
	//对应单位管理员列表
	public function adminList()
    {

		$unitsid = $this->request->param('unitid') ? $this->request->param('unitid/d') : 0;
		$adminuserid = $this->request->param('adminuserid') ? $this->request->param('adminuserid') : 0;
		$reg = $this->request->param('reg') ? getStr($this->request->param('reg')) : '';
		if(!$unitsid){
			$data =  ['msg'=>'缺少参数','code'=>'500','data'=>[]];
		}
			try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new UnitsServiceClient(NULL);
				\ApiClient::build($api);

				$engprojectDo = new UnitsDTO();
				$engprojectDo->unitid = $unitsid;
				$engprojectDo->reg = $reg;
				$engprojectDo->userid	= $adminuserid;
				$result = $api->adminList($engprojectDo);

				
				
				
				//checkstate 1是选中 0是未选中
				if($result->code){
					$datas = json_decode($result->message,true);
					$data =  ['msg'=>'成功','code'=>'200','data'=>$datas];
				} else {
					$data =  ['msg'=>$result->message,'code'=>'400','data'=>[]];
				}
			} catch (Exception $ex) {
				$data =  ['msg'=>'失败','code'=>'500','data'=>[]];
			}
			
		
		return json_encode($data);
	}

/**********************************************************/
    
	
	public function index()
    {
		echo  5;exit;
		if(Session::get('user_name')==''){
			//header("Location: http://www.aa.com/admin/cheshi/login"); 
			echo 2;
			exit;
		}
		return $this->view->fetch();
	}
	public function login()
    {

		return $this->view->fetch();
	}
	
    public function index111()
    {

			$role_id = 2;//权限组
			$username = 'admin';
			$plaform_id = 1;
			$userid = 1;
            if (!$role_id || !$username || !$userid || !$plaform_id) {
				$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
				return json_encode($data);
            }
			try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AuthorityServiceClient(NULL);
				\ApiClient::build($api);
				$engprojectDo = new AuthorityRequestDTO();
				$engprojectDo->id = $role_id;
				$engprojectDo->username	= $username;
				$engprojectDo->filename['plaform_id']	= $plaform_id;
				$engprojectDo->filename['userid']	= $userid;
				$result = $api->accessList($engprojectDo);
	
				$results = list_to_tree($result->data, "id", "pid", "ChildNodes");

				$this->view->assign('results', $results);

			} catch (Exception $ex) {
				$data = ['msg'=>'获取失败','code'=>'400','data'=>[]];
				var_dump($data);exit;
			}
			

		return $this->view->fetch();
    }
	
	public function aa()
    {
		$role_id = $this->request->param('role_id/d');
		$role_id = 2;
            if (!$this->request->isPost() || !$role_id) {
				$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
				return json_encode($data);
            }
			try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AuthorityServiceClient(NULL);
				\ApiClient::build($api);

				$engprojectDo = new AuthorityRequestDTO();
				$engprojectDo->filename = $this->request->post()["Bike"];
				$engprojectDo->filename['role_id']	= $role_id;
				$result = $api->authorized($engprojectDo);
		
				//checkstate 1是选中 0是未选中
				$data =  ['msg'=>'获取成功','code'=>'200','data'=>$results];
			} catch (Exception $ex) {
				$data = ['msg'=>'获取失败','code'=>'400','data'=>[]];
			}
		
	}
	
	public function bb(){
		$plaform_id = 2;
			$userid = 1;
			$role_id = 2;
            if (!$plaform_id || !$userid || !$role_id) {
				$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
				return json_encode($data);
            }
			try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AuthorityServiceClient(NULL);
				\ApiClient::build($api);
				
				$engprojectDo = new AuthorityRequestDTO();
				$engprojectDo->filename = $this->request->post()["Bike"];
				$engprojectDo->filename['plaform_id'] = $plaform_id;
				$engprojectDo->filename['userid']	= $userid;
				$engprojectDo->filename['role_id']	= $role_id;

				$result = $api->userAuthorized($engprojectDo);

				//checkstate 1是选中 0是未选中
				$data =  ['msg'=>'获取成功','code'=>'200','data'=>$results];
			} catch (Exception $ex) {
				$data = ['msg'=>'获取失败','code'=>'400','data'=>[]];
			}
			return json_encode($data);
		
	}
	public function checkLogin()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
			
			$username = $this->request->post('username') ? $this->request->post('username') : '';
		$password = $this->request->post('password') ? $this->request->post('password') : '';
		$code = $this->request->post('code') ? $this->request->post('code') : '';
            // 提交
            if (empty($username) || empty($password) || empty($code)) {
				$data = ['msg'=>'缺少必要参数','code'=>'400','data'=>[]];
				return json_encode($data);
            }
			/*if(Session::get('login_code')!=$code){
				$data = ['msg'=>'验证码输入错误，请重新输入','code'=>'400','data'=>[]];
				return json_encode($data);
			}*/
			
            try {
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $api = new AdminloginServiceClient(NULL);
            \ApiClient::build($api);
            $engprojectDo = new AdminloginRequestDTO();
            $engprojectDo->username = $username;
			$engprojectDo->password = $password;
            $result = $api->login($engprojectDo);
			if($result->code){
				$datas = $result->data[0];

                Session::set('reg', $datas['reg']);
                Session::set('user_name', $datas['name']);
                Session::set('real_name', $datas['realname']);
				Session::set('userid', $datas['userid']);
                Session::set('plaform_id', $datas['plaform_id']);
				Session::set('plaform_name', $datas['plaform_name']);
				Session::set(Config::get('rbac.user_auth_key'), $datas['userid']);
				return ajax_return_adv('登录成功', '');
			} else {

				 return ajax_return_adv_error($result->message);
			}
        } catch (Exception $ex) {
       
			  return ajax_return_adv_error('登录失败');
        }
		}
	
    }
	
	public function alist()
    {
		
		$plaform_id = Session::get('plaform_id');

		$page = $this->request->param('p')>1 ? $this->request->param('p/d') : 1;
		$pagesize = $this->request->param('num')>0 ? $this->request->param('num/d') : 10;
         if ($plaform_id<0) {
			$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
			return json_encode($data);
        }
		$p = ($page-1)*$pagesize;
		$adminRole = new \app\common\model\AdminRole();
		//$child_plaform = getChildAdminRegByPlaformId($plaform_id,0);
	
			$child_plaform = [Session::get('reg')];
		

		$cond = 'isdelete=0';
		if(!empty($child_plaform)){
			$cond .= " and admin_reg in('".implode("','",$child_plaform)."')";
		}
		
		if($this->request->param('status')>-1){

			$cond .= ' and status='.$this->request->param('status');
		}
		
		if($this->request->param('title')){
			$cond .= " and (name like '%{$this->request->param('title')}%' or remark like '%{$this->request->param('title')}%' )";
			
		}
		

		$list = $adminRole->field('id,pid,name,status')->where($cond)->limit($p.','.$pagesize)->select();
		$autList = [];
		foreach($list as $v){
			$autList[] = ['id'=>$v->id,'pid'=>$v->pid,'name'=>$v->name,'status'=>$v->status];
		}
		$num = $adminRole->field('count(*) num')->where($cond)->find();
		$page = new \Pagesd($num['num'], $pagesize, $page, '/admin/cheshi/alist/p/{page}', 2); 
		$pages= $page->myde_write(); 
		$this->view->assign("pages", $pages);
		$this->view->assign('autList', $autList);
		$this->view->assign('num',$num['num']);
		return $this->view->fetch();
	}
	public function aadd()
    {
		if ($this->request->isPost()) {


			$plaform_id = Session::get('plaform_id');
			$name = $this->request->param('name');
			$pid = $this->request->param('pid/d');
			$status= $this->request->param('status/d');
			$userid = Session::get('userid');
			$remark = $this->request->param('remark');
			$admin_reg = Session::get('reg');
			 if ($name=='' || $plaform_id<0) {
				$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
				return json_encode($data);
			}
			$adminRole = new \app\common\model\AdminRole();
			$data = [
					//'pid'=>$pid,
					'pid'=>0,
					'name'=>$name,
					'remark'=>$remark,
					'plaform_id'=>$plaform_id,
					'status'=>$status,
					'create_time'=>time(),
					'update_time'=>time(),
					'admin_reg'=>$admin_reg,
					];
	
			$adminRole->insert($data);
			echo "<script>location.href = 'http://www.aa.com/admin/cheshi/alist.html';</script>";
		} else {
		return $this->view->fetch();
		}
	}
	
	
	
	
	public function userlist()
    {
		
		$plaform_id = Session::get('plaform_id');
		$role_id = $this->request->param('roleid/d');
		$page = $this->request->param('p')>1 ? $this->request->param('p/d') : 1;
		$pagesize = $this->request->param('num')>0 ? $this->request->param('num/d') : 10;
         if ($plaform_id<0) {
			$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
			return json_encode($data);
        }
		$p = ($page-1)*$pagesize;
		$adminRole = new \app\common\model\AdminUser();
		$child_plaform = [];
		if($plaform_id){
		$child_plaform = getChildAdminRegByPlaformId($plaform_id,0);
		//$child_plaform = [Session::get('reg')];
		
		}
		$cond = 'isdelete=0 and id>1';
		
		$db_role_user = Db::name('AdminRoleUser')->where(['role_id'=>$role_id])->select();
		foreach($db_role_user as $v){
			$role_user[$v['user_id']] = $v['role_id'];
		}

		$list = $adminRole->field('id,account name,realname,idcard,mobile')->where($cond)->limit($p.','.$pagesize)->select();

		$num = $adminRole->field('count(*) num')->where($cond)->find();
		$this->view->assign('role_id', $role_id);
		$this->view->assign('role_user', $role_user);
		$this->view->assign('autList', $list);
		$this->view->assign('num',$num['num']);
		return $this->view->fetch();
	}
	
	public function addGroups()
    {
		$userid = trim($this->request->param('userid'),"'");
		$role_id = $this->request->param('role_id/d');
		$userid = explode(',',$userid);

		$adminRole = Db::name('adminAccess');
		$node_id = $adminRole->where(['role_id'=>$role_id])->field('node_id,level,pid')->select();

		$db_role_users = new \app\common\model\AdminRoleUser();
		$role_user =$db_role_users->where(['role_id'=>$role_id])->select();
		foreach($role_user as $v){
			$roleuser[] = $v['user_id'];
		}
		if(is_array($userid)){
			foreach($userid as $v){
				if(in_array($v,$roleuser)){
					continue;
				}
				$insert_all[] = [
                        "role_id" => $role_id,
                        "user_id" => $v,
                    ];
				self::usergrops($v,$node_id,$role_id);
			}

			  $db_role_users->insertAll($insert_all);
			
		} else {
			if(in_array($userid,$roleuser)) echo '成功';exit;
			self::usergrops($userid,$node_id,$role_id);
			$insert_all = [
                        "role_id" => $role_id,
                        "user_id" => $v,
                    ];
			 $db_role_users->insert($insert_all);
		}
		
		echo '成功';
		
	}
	
	public function usergrops($userid,$node_id,$role_id){
		$db_role_user = Db::name('AdminUserAccess');
		if(!empty($node_id)){
			$insert_allc=[];
			$user = $db_role_user->where(['user_id'=>$userid,'role_id'=>$role_id])->find();
			if(!empty($user)) return false;
			
			foreach($node_id as $vc){
				
					 $insert_allc[] = [
							"user_id" => $userid,
							"node_id" => $vc['node_id'],
							"level"   => $vc['level'],
							"pid"     => $vc['pid'],
							"role_id"     => $role_id,
						];
				}
				$db_role_user->insertAll($insert_allc);
				
		
		}
	}
	
	
	public function userauthorized()
    {
		$role_id = $this->request->param('roleid/d');
		$userid = $this->request->param('userid/d');
		if ($this->request->isPost()) {
			$datas = $this->request->post();
			try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AuthorityServiceClient(NULL);
				\ApiClient::build($api);
				
				$engprojectDo = new AuthorityRequestDTO();
				$engprojectDo->filename = $this->request->post()['node'];

				$engprojectDo->filename['userid']	= $userid;
				$engprojectDo->filename['role_id']	= $role_id;

				$result = $api->userAuthorized($engprojectDo);

				//checkstate 1是选中 0是未选中
				if($result->code){
						echo "<script>alert('成功');location.href = '/admin/cheshi/userlist/roleid/".$role_id."';</script>";
				} else {
					echo "<script>alert('失败');location.href = '/admin/cheshi/userlist/roleid/".$role_id."';</script>";
				}
			} catch (Exception $ex) {
				echo "<script>alert('失败');location.href = '/admin/cheshi/userlist/roleid/".$role_id."';</script>";
			}
		
		} else {
			
			$username =  Session::get('user_name');

            if (!$role_id || !$username || !$userid ) {
				$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
				return json_encode($data);
            }
			try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AuthorityServiceClient(NULL);
				\ApiClient::build($api);
				$engprojectDo = new AuthorityRequestDTO();
				$engprojectDo->id = $role_id;
				$engprojectDo->username	= $username;
				$engprojectDo->filename['userid']	= $userid;
				$result = $api->accessuserList($engprojectDo);

				$results = list_to_tree($result->data, "id", "pid", "ChildNodes");

				$this->view->assign('results', $results);

			} catch (Exception $ex) {
				$this->view->assign('results', []);
			}
			

		$this->view->assign('role_id',$role_id);
		$this->view->assign('userid',$userid);
		return $this->view->fetch();
		}
	}
	public function deletes()
    {

		$userid = $this->request->param('userid/d');
		$role_id = $this->request->param('role_id/d');
		Db::name('AdminRoleUser')->where(['user_id'=>$userid,'role_id'=>$role_id])->delete();
		Db::name('AdminUserAccess')->where(['user_id'=>$userid,'role_id'=>$role_id])->delete();
		echo '成功';
	}
}
